<?php

include "validate.php";
include "db_con.php";

print_r($_POST);

if (isset($_POST["sensor"]))
	$sensor = $_POST["sensor"];
else
	$sensor = "";
if (isset($_POST["record"]))
	$record = $_POST["record"] + 1;
else
	$record = "";
if (isset($_POST["disable_all"]))
	$all = $_POST["disable_all"];
else
	$all = "";
if (isset($_POST["disable"]))
	$disable = $_POST["disable"];
else
	$disable = "";

if (strlen($sensor)<1)
{
	$_SESSION['message'] = "No Sensor Selected";
	header("Location:sensor_management.php");
}
if (strlen($all)>0)
{
	$query = "	SELECT sensor_id AS ID 
			FROM sensor 
			WHERE name = '" . $sensor . "';";
	
	$result = mysql_query($query);
	
	if ($row = mysql_fetch_array($result))
	{
		$sensor_id = $row['ID'];
		
		$query = "	UPDATE records 
				SET is_active = 0, is_update = 1 
				WHERE sensor_id = '" . $sensor_id . "';";
		mysql_query($query);
		$_SESSION['message'] = "Sensors Updated";
		header("Location:sensor_management.php");
	}
	else
	{
		$_SESSION['message'] = "ERROR";
		header("Location:sensor_management.php");
	}
}
if (strlen($disable)>0 && strlen($record)>0)
{
	$query = "	SELECT records_id AS ID 
			FROM (
				SELECT records_id 
				FROM records 
				INNER JOIN sensor ON sensor.sensor_id = records.sensor_id 
				WHERE sensor.name = '" . $sensor . "' 
				ORDER BY records_id ASC 
				LIMIT " . $record . " 
			) AS x
			ORDER BY records_id DESC;";

	$result = mysql_query($query);

	if ($row = mysql_fetch_array($result))
	{
		$record_id = $row['ID'];

		$query = "	UPDATE records 
				SET is_active = 0, is_update = 1  
				WHERE records_id = '" . $record_id . "';";

		mysql_query($query);
		$_SESSION['message'] = "Sensor Updated";
		header("Location:sensor_management.php");
	}
	else
	{
		$_SESSION['message'] = "ERROR";
		header("Location:sensor_management.php");
	}
}
else if (strlen($disable)==0 && strlen($record)>0)
{
	$query = "	SELECT records_id AS ID 
			FROM (
				SELECT records_id 
				FROM records 
				INNER JOIN sensor ON sensor.sensor_id = records.sensor_id 
				WHERE sensor.name = '" . $sensor . "' 
				ORDER BY records_id ASC 
				LIMIT " . $record . " 
			) AS x
			ORDER BY records_id DESC;";


	$result = mysql_query($query);

	if ($row = mysql_fetch_array($result))
	{
		$record_id = $row['ID'];

		$query = "	UPDATE records 
				SET is_active = 1, is_update = 1 
				WHERE records_id = '" . $record_id . "';";

		mysql_query($query);
		$_SESSION['message'] = "Sensor Updated";
		header("Location:sensor_management.php");
	}
	else
	{
		$_SESSION['message'] = "ERROR";
		header("Location:sensor_management.php");
	}
}
?>
